package com.wyp.didishige.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.wyp.didishige.activity.MainActivity;
import com.wyp.didishige.activity.UserInfoActivity;
import com.wyp.didishige.adapter.NearPeopleAdapter;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.ToastUtil;
import com.wyp.didishige.wiget.xlist.XListView;
import com.wyp.didishige.R;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.FindListener;

/**
 * 附近的人
 */
public class NearFragment extends FragmentBase implements XListView.IXListViewListener, AdapterView.OnItemClickListener {

    private Activity mActivity;
    private View mView;
    BmobGeoPoint geoPoint;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    XListView mListView;
    NearPeopleAdapter adapter;
    public Boolean sex = null;
    List<User> nears = new ArrayList<User>();
    User user;
    private SwipeRefreshLayout hullSwipe = null;

    public static NearFragment newInstance(boolean sex){
        NearFragment fragment=new NearFragment();
        fragment.sex = sex;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initParamter();
        user = userManager.getCurrentUser(User.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_near, null);
        init();
        return mView;
    }

    @Override
    protected void initParamter() {
        super.initParamter();
        mActivity = getActivity();
        adapter = new NearPeopleAdapter(mActivity, nears);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        hullSwipe = (SwipeRefreshLayout) mView.findViewById(R.id.hullSwipe);

        mListView = (XListView) mView.findViewById(R.id.list_near);
        // 首先不允许加载更多
        mListView.setPullLoadEnable(false);
        // 允许下拉
        mListView.setPullRefreshEnable(false);
        // 设置监听器
        mListView.setXListViewListener(this);
    }

    @Override
    protected void initWidgetState() {
        super.initWidgetState();
        mListView.setAdapter(adapter);
        hullSwipe.setColorSchemeResources(R.color.btn_blue, R.color.vip_male);
        hullSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                getNearByList(true);
            }
        });

        getLocation();
    }

    @Override
    protected void initWidgetListener() {
        super.initWidgetListener();
        mListView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        User user = (User) adapter.getItem(position);
        Bundle bundle = new Bundle();

        bundle.putString(Config.KEY_USER_ID, user.getObjectId());
        IntentUtil.start_activity(mActivity, UserInfoActivity.class, bundle);
    }

    public void setSex(Boolean b) {
        sex = b;
        onRefresh();
    }

    @Override
    public void onRefresh() {
        hullSwipe.setRefreshing(true);
        page = 0;
        getNearByList(true);
    }

    private void refreshLoad() {
        if (mListView.getPullLoading()) {
            mListView.stopLoadMore();
        }
        if (mListView.getPullRefreshing()) {
            mListView.stopRefresh();
        }
    }

    @Override
    public void onLoadMore() {
        getNearByList(false);
    }

    /**
     * 定位
     */
    private void getLocation() {
        // 定位初始化
        mLocClient = new LocationClient(getActivity());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
//        option.setScanSpan(2000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                geoPoint = new BmobGeoPoint(location.getLongitude(), location.getLatitude());
            } else {
                // 无定位数据默认北京中心
                double cLat = 39.909230;
                double cLon = 116.397428;
                geoPoint = new BmobGeoPoint(cLon, cLat);
            }

            onRefresh();
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    int page = 0;
    int limit = 20;

    private void getNearByList(final boolean isReferesh) {
        if (geoPoint==null){
            getLocation();
            ToastUtil.showShort(getActivity(),"尚未定位地址信息");
            return;
        }
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereWithinKilometers("location", geoPoint, 5000);
        if (sex != null) {
            query.addWhereEqualTo("sex", sex);
        }
        query.addWhereNotEqualTo("objectId", user.getObjectId());
        query.setLimit(limit);
        query.setSkip(limit * page);
        query.order("-updatedAt");
        query.findObjects(getActivity(), new FindListener<User>() {
            @Override
            public void onSuccess(List<User> Dynamics) {
                if (Dynamics != null) {
                    if (isReferesh) {
                        adapter.setList(Dynamics);
                    } else {
                        adapter.addAll(Dynamics);
                    }
                    page++;
                }
            }

            @Override
            public void onFinish() {
                refreshLoad();
                refreshLoad();
                hullSwipe.setRefreshing(false);
            }

            @Override
            public void onError(int i, String s) {
                ShowToast(s);
            }
        });
    }

}
